"""
对话管理器，用于管理用户对话历史和上下文
"""
import time
import uuid
from typing import Dict, List, Optional, Any
from models.schemas import Message, ConversationContext
from utils.logger import setup_logger

class ConversationManager:
    """对话管理器，负责维护对话上下文和历史记录"""
    
    def __init__(self, max_conversations: int = 1000, ttl: int = 3600):
        """
        初始化对话管理器
        
        参数:
            max_conversations: 最大对话数量
            ttl: 对话超时时间（秒）
        """
        self.conversations: Dict[str, ConversationContext] = {}
        self.max_conversations = max_conversations
        self.ttl = ttl
        # 使用自动文件日志功能
        self.logger = setup_logger(name="conversation_manager", level="debug")
    
    def create_conversation(self, server_id: Optional[str] = None) -> str:
        """
        创建新的对话
        
        参数:
            server_id: 关联的服务器ID
            
        返回:
            conversation_id: 对话ID
        """
        # 清理过期对话
        self._cleanup_expired()
        
        # 如果达到最大对话数，删除最旧的对话
        if len(self.conversations) >= self.max_conversations:
            self._remove_oldest()
        
        # 创建新对话
        conversation_id = str(uuid.uuid4())
        self.conversations[conversation_id] = ConversationContext(
            conversation_id=conversation_id,
            server_id=server_id,
            last_active=time.time(),
            messages=[]
        )
        
        self.logger.info(f"创建新对话: {conversation_id}, 服务器: {server_id or '自动'}")
        return conversation_id
    
    def get_conversation(self, conversation_id: str) -> Optional[ConversationContext]:
        """
        获取对话上下文
        
        参数:
            conversation_id: 对话ID
            
        返回:
            对话上下文，如果不存在则返回None
        """
        # 更新最后活跃时间
        if conversation_id in self.conversations:
            self.conversations[conversation_id].last_active = time.time()
            return self.conversations[conversation_id]
        
        self.logger.warning(f"尝试获取不存在的对话: {conversation_id}")
        return None
    
    def add_message(self, conversation_id: str, message: Message) -> bool:
        """
        添加消息到对话历史
        
        参数:
            conversation_id: 对话ID
            message: 消息内容
            
        返回:
            是否成功添加
        """
        conversation = self.get_conversation(conversation_id)
        if not conversation:
            self.logger.warning(f"尝试向不存在的对话添加消息: {conversation_id}")
            return False
        
        conversation.messages.append(message)
        self.logger.debug(f"向对话 {conversation_id} 添加消息: {message.role}")
        return True
    
    def get_messages(self, conversation_id: str) -> List[Message]:
        """
        获取对话历史消息
        
        参数:
            conversation_id: 对话ID
            
        返回:
            消息列表
        """
        conversation = self.get_conversation(conversation_id)
        if not conversation:
            self.logger.warning(f"尝试获取不存在的对话消息: {conversation_id}")
            return []
        
        return conversation.messages
    
    def set_server_id(self, conversation_id: str, server_id: str) -> bool:
        """
        设置对话关联的服务器ID
        
        参数:
            conversation_id: 对话ID
            server_id: 服务器ID
            
        返回:
            是否成功设置
        """
        conversation = self.get_conversation(conversation_id)
        if not conversation:
            return False
        
        conversation.server_id = server_id
        self.logger.info(f"对话 {conversation_id} 关联到服务器: {server_id}")
        return True
    
    def get_server_id(self, conversation_id: str) -> Optional[str]:
        """
        获取对话关联的服务器ID
        
        参数:
            conversation_id: 对话ID
            
        返回:
            服务器ID，如果未关联则返回None
        """
        conversation = self.get_conversation(conversation_id)
        if not conversation:
            return None
        
        return conversation.server_id
    
    def delete_conversation(self, conversation_id: str) -> bool:
        """
        删除对话
        
        参数:
            conversation_id: 对话ID
            
        返回:
            是否成功删除
        """
        if conversation_id in self.conversations:
            del self.conversations[conversation_id]
            self.logger.info(f"删除对话: {conversation_id}")
            return True
        
        return False
    
    def update_metadata(self, conversation_id: str, key: str, value: Any) -> bool:
        """
        更新对话元数据
        
        参数:
            conversation_id: 对话ID
            key: 元数据键
            value: 元数据值
            
        返回:
            是否成功更新
        """
        conversation = self.get_conversation(conversation_id)
        if not conversation:
            return False
        
        conversation.metadata[key] = value
        return True
    
    def get_metadata(self, conversation_id: str, key: str) -> Optional[Any]:
        """
        获取对话元数据
        
        参数:
            conversation_id: 对话ID
            key: 元数据键
            
        返回:
            元数据值，如果不存在则返回None
        """
        conversation = self.get_conversation(conversation_id)
        if not conversation or key not in conversation.metadata:
            return None
        
        return conversation.metadata[key]
    
    def _cleanup_expired(self):
        """清理过期对话"""
        current_time = time.time()
        expired = [
            conv_id for conv_id, conv in self.conversations.items()
            if current_time - conv.last_active > self.ttl
        ]
        
        for conv_id in expired:
            del self.conversations[conv_id]
        
        if expired:
            self.logger.info(f"清理 {len(expired)} 个过期对话")
    
    def _remove_oldest(self):
        """删除最旧的对话"""
        if not self.conversations:
            return
        
        oldest_id = min(
            self.conversations.keys(),
            key=lambda k: self.conversations[k].last_active
        )
        
        del self.conversations[oldest_id]
        self.logger.info(f"删除最旧的对话: {oldest_id}")